﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using ZLWeb.WebApiEntityBas;
using ZLWeb.WebApiEntityBase;

namespace ZL.Web.Utility.Http
{
    public class HttpNoCompressionClient : IHttpClient
    {
        public T HttpGet<T>(string url, IdentityEntity Identity)
        {
            try
            {
                Func<HttpContent, string> stringFunc = hc =>
                {
                    var responsejson = hc.ReadAsStringAsync().Result;
                    return responsejson;
                };
                return HttpHelper.HttpRequestGet<T>(url, HttpHelper.HttpHeaderHandler(Identity), stringFunc);
            }
            catch (AggregateException ex)
            {
                var innerEx = ex.InnerExceptions[0];
                if (innerEx is HttpRequestException)
                {
                    throw new CommonException(innerEx.InnerException.Message);
                }
                return default(T);
            }
            catch (NotFindAccidException ex)
            {
                throw new NotFindAccidException(ex.Message);
            }
            catch (Exception exception)
            {
                throw new CommonException(exception.Message);
                //var Message = exception.Message;
            }
            //catch (System.Exception exception)
            //{
            //    var Message = exception.Message;
            //}

        }

        public T HttpPost<P, T>(P param, string url, IdentityEntity Identity)
        {
            try
            {
                HttpContent httpContent = null;
                if (param != null)
                {
                    var requestjson = JsonConvert.SerializeObject(param);
                    httpContent = new StringContent(requestjson);
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }
                Func<HttpContent, string> stringFunc = hc =>
                {
                    var responsejson = hc.ReadAsStringAsync().Result;
                    return responsejson;
                };
                return HttpHelper.HttpRequestPost<T>(url,
                    HttpHelper.HttpHeaderHandler(Identity), httpContent, stringFunc);
            }

            catch (NotFindAccidException ex)
            {
                throw new NotFindAccidException(ex.Message);
            }
            catch (AggregateException ex)
            {
                var innerEx = ex.InnerExceptions[0];
                if (innerEx is HttpRequestException)
                {
                    throw new CommonException(innerEx.InnerException.Message);
                }
            }
            catch (Exception exception)
            {
                throw new CommonException(exception.Message);
                //var Message = exception.Message;
            }
            return default(T);
        }
    }
}